<template>
  <div class="current-prriod-quantities">
    <div class="model-title">2、本期完成工程量</div>
    <div class="top">
        <div class="left">
            <el-tabs v-model="leftTab" :stretch="true">
                <el-tab-pane label="章次" name="1">
                <div v-if="chapterList.length > 0" v-loading="leftLoading" class="list">
                    <div v-for="(item,index) in chapterList" :key="`project-${index}`" :class="['list-item',chapterSequence.id === item.id ? 'active':'' ]" @click="handleChapterClick(item)">
                        <TextTooltip   :content="`第${item.listSubitemCode}章 ${item.listSubitemName}`" :ref-name="`${item.id}-${item.listSubitemName}`" :class-name="`project-item`"></TextTooltip>
                    </div>
                </div>
                </el-tab-pane>
                <el-tab-pane label="计日工" name="2">
                <div v-if="chapterList.length > 0" v-loading="leftLoading" class="list">
                    <div v-for="(item,index) in chapterList" :key="`project-${index}`" :class="['list-item',chapterSequence.id === item.id ? 'active':'' ]" @click="handleChapterClick(item)">
                        <TextTooltip   :content="item.listSubitemName" :ref-name="`${item.id}-${item.listSubitemName}`" :class-name="`project-item`"></TextTooltip>
                    </div>
                </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div class="right">
            <div class="model-title">
                <div style="font-weight: 600;margin-right: 4px;">第{{ chapterSequence.listSubitemCode }}章 {{ chapterSequence.listSubitemName }}</div>
                <div>（合计：￥{{ total }}）</div>
            </div>
            <el-form slot="form" :inline="true" size="medium">
                <el-form-item label="清单子目编码">
                    <el-input v-model="query.listSubitemCode" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label="清单子目名称">
                    <el-input v-model="query.listSubitemName" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item>
                    <BaseButton @click="handleFilter">查询</BaseButton>
                    <BaseButton type="second" @click="resetConditions()">重置</BaseButton>
                </el-form-item>
            </el-form>
            <BaseTable 
                ref="table"
                v-loading="listLoading"
                style="margin-top: 8px;" 
                :data="list" 
                :columns="columns" 
                highlight-current-row 
                default-expand-all
                height="500px"
                row-key="id"
                :tree-props="{children: 'childrenList',hasChildren: ''}"
                >
                <template #parentCode="{ scope: { row } }">
                    <div class="icon-flex">
                        <IconSvg v-if="!row.expanded && row.expanded !== undefined && row.hasChildren === 1" icon-class="file" class="file-icon"></IconSvg>
                        <IconSvg v-if="(row.expanded || row.expanded === undefined) && row.hasChildren === 1" icon-class="file-open" class="file-icon"></IconSvg>
                        <IconSvg v-if="row.hasChildren === 2" icon-class="catalogue" class="catalogue-icon"></IconSvg>
                        {{ row.listSubitemCode }}
                    </div>
                </template>
                <!-- 本期完成数量 -->
                <template #currentPeriodQuantity="{ scope: { row, } }">
                    <div v-if="row.hasChildren === 2 && row.unitCode !== 'zonge'">
                        <el-form :ref="`formTable-${row.id}-currentPeriodQuantity`"  :model="row">
                            <el-form-item 
                            label="" 
                            prop="currentPeriodQuantity"
                            :rules="[
                            { 
                                type:'number', 
                                validator: validConfig[row.unitDecimalPlace] ? validConfig[row.unitDecimalPlace].validfun : checkPositiveInteger, 
                                trigger:'blur' 
                            }
                               
                            ]"
                           >
                                <el-input 
                                v-model.number="row.currentPeriodQuantity" 
                                type="number"
                                placeholder="请输入" 
                                clearable 
                                 />
                                </el-form-item>
                        </el-form>
                    </div>
                    
                </template>
                <!-- 本期计量金额 , 本期完成金额-->
                <template #currentPeriodMsAmount="{ scope: { row } }">
                    <div v-if="row.hasChildren === 2 && row.unitCode === 'zonge'">
                        <el-form :ref="`formTable-${row.id}-currentPeriodMsAmount`"  :model="row">
                            <el-form-item 
                            label="" 
                            prop="currentPeriodMsAmount"
                           :rules="[
                            { 
                                type:'number', 
                                validator: checkTwoDecimal, 
                                trigger:'blur' 
                            }
                           ]"
                           >
                                <el-input 
                                v-model="row.currentPeriodMsAmount" 
                                type="number"
                                placeholder="请输入" 
                                clearable
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                    <div v-if=" row.hasChildren === 2 && row.unitCode !== 'zonge'">
                        {{ countCurrentPeriodQuantity(row.price, row.currentPeriodQuantity) }}
                    </div>
                </template>
                <!-- 备注 -->
                <template #remark="{ scope: { row, $index} }">
                    <el-form :ref="`formTable-${$index}-currentPeriodQuantity`"  :model="row">
                         <el-form-item v-if="row.hasChildren === 2" label="" prop="remark">
                            <el-input v-model="row.remark" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-form>
                </template>
            </BaseTable>
            <Pagination
                class="pagination"
                :current-page.sync="page.pageNo"
                :page-size.sync="page.pageSize"
                :total="page.total"
                @size-change="getList"
                @current-change="getList"
            />
        </div>
    </div>
    <div class="btn">
      <BaseButton type="second" @click="handleBack">上一步</BaseButton>
      <BaseButton type="second" @click="handleSave(true)">保存</BaseButton>
      <BaseButton @click="handleNext">下一步</BaseButton>
    </div>
  </div>
</template>
<script>
import { ProjectLedgerModel } from '@/models'
import calcNumber from 'calc-number'
import { revalueField} from '@/utils/index.js'
import message from '@/router/modules/message'
export default {
    props: {
        curStep: {
            type: [Number],
            required: true
        },
        // 工程项目信息
        info: {
            type: Object,
            default: () => {}
        },
        // 申请ID
        id: {
            type: [Number, String],
            default: ''
        },
    },
    data() {
        return {
            leftTab: '1', // 章次，计日工
            chapterList: [],
            model: new ProjectLedgerModel(),
            projectId: '', // 项目ID
            chapterSequence: {}, // 当前选择的章次或者计日工
            query: {
                id: '', // 申请记录ID
                billQuantitiesType: '', // 工程类型：普通类型、计日工
                chapterSequenceCode: '', // 章次编码
                listSubitemCode: '', // 清单子目编码
                listSubitemName: ''// 清单子目名称
            },
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            columns: [
                {
                    slot: 'parentCode',
                    attrs: {
                        label: '清单子目编码',
                        prop: 'parentCode',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '清单子目名称',
                        prop: 'listSubitemName',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '单位',
                        prop: 'unitSymbol',
                        width: '80',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '数量',
                        prop: 'quantity',
                        
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '单价（元）',
                        prop: 'price',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '合价（元）',
                        prop: 'amount',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'currentPeriodQuantity',
                    attrs: {
                        label: '本期完成数量',
                        prop: 'currentPeriodQuantity',
                        width: '150'
                    }
                },
                {
                    slot: 'currentPeriodMsAmount',
                    attrs: {
                        label: '本期计量金额（元）',
                        prop: 'currentPeriodMsAmount',
                        width: '150'
                    }
                },
                {
                    slot: 'remark',
                    attrs: {
                        label: '备注',
                        prop: 'remark',
                        width: '150'
                    }
                },
            ],
            list: [],
            leftLoading: false,
            listLoading: false,
            chapterBesidesPageTotal: 0, // 整章的合计减去本页的合计
            chapterTotal: 0, // 整章的合计
            isFirst: true,
            rules: {},
            validConfig: {
                // 0: 'checkPositiveInteger',
                // 2: 'checkTwoDecimal',
                // 3: 'checkThreeDecimal',
                0: {validfun: this.checkPositiveInteger, msg: '输入数字应为正整数'},
                2: {validfun: this.checkTwoDecimal, msg: '输入数字最多保留两位小数，且为正数'},
                3: {validfun: this.checkThreeDecimal, msg: '输入数字最多保留三位小数，且为正数'}
            }
        }
    },
    computed: {
        // 本页的合计
        pageTotal() {
            const data = this.sumLeafValues(this.list)
            return data
        },
        // 合计
        total() {
            return calcNumber(`${Number(this.chapterBesidesPageTotal)} + ${Number(this.pageTotal)}`)
        },
       
    },
    watch: {
        leftTab: {
            handler() {
                this.handleSave()
                this.query.billQuantitiesType = Number(this.leftTab)
                this.chapterSequence = {}
                this.getChapterList()
            }
        },
        curStep: {
            immediate: true,
            handler(val) {
                if (val === 1) {
                    this.isFirst = true
                    this.getChapterList()
                }
            }
        },
        info: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.projectId = this.info.projectId
                }
            }
        },
        id: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.query.id = this.id
                }
            }
        }
        
    },
    methods: {
        // 临时计算本期计量金额
        countCurrentPeriodQuantity(price, amount) {
            let sPrice = price
            let sAmount = amount
            if (!Number(price)) {
                sPrice = 0
            }
            if (!Number(amount)) {
                sAmount = 0
            }
            let value = calcNumber(`${sPrice} * ${sAmount}`)
            const isThreeDec = this.hasMoreThanThreeDecimals(value)
            if (isThreeDec) {
                value = this.roundToDecimalPlace(value, 2)
            }
            return value
        },
        // 保留到指定的小数位数
        roundToDecimalPlace(number, decimalPlaces) {
            const factor = Math.pow(10, decimalPlaces)
            return Math.round(number * factor) / factor
        },
        // 是否有三位小数
        hasMoreThanThreeDecimals(num) {
            // 将数字转换为字符串
            const numStr = num.toString()
            // 查找小数点
            const dotIndex = numStr.indexOf('.')
            // 如果没有小数点或者小数点后只有两位数字，则不超过三位小数
            if (dotIndex === -1 || numStr.length - dotIndex - 1 <= 2) {
                return false
            }
            // 如果小数点后有超过三位数字，则返回true
            return true
        },
        // 获取左侧列表
        getChapterList() {
            const queryData = {
                msType: 2,
                type: Number(this.leftTab),
                projectId: this.projectId
            }
            this.model.chapterListById({...queryData}).then(res => {
                if (res) {
                    this.chapterList = [...res]
                    // 保留上一步的操作,初始无值默认第一个
                    if (JSON.stringify(this.chapterSequence) === '{}' && this.chapterList.length) {
                        this.chapterSequence = {...this.chapterList[0]}
                        this.query.chapterSequenceCode = this.chapterList[0].listSubitemCode
                    }
                    this.getList()
                } else {
                    this.chapterList = []
                }
            })
        },       
        // 左侧点击
        handleChapterClick(item) {
            this.handleSave()
            this.chapterSequence = {...item}
            this.query.chapterSequenceCode = item.listSubitemCode
            const alreadySave = true
            this.getList(alreadySave)
        },
        // 筛选
        handleFilter() {
            this.page.pageNo = 1
            this.getList()
        },
        // 重置
        resetConditions() {
            this.query.listSubitemCode = ''
            this.query.listSubitemName = ''
            this.handleFilter()
        },
        // 查询右侧列表
        getList(alreadySave = false) {
            // 初次不保存
            if (!alreadySave && !this.isFirst) {
                this.handleSave()
            }

            this.listLoading = true
            this.model.currentPeriodPageList({...this.page, ...this.query}).then(res => {
                if (res) {
                    this.list = revalueField(res.list, ['currentPeriodMsAmount', 'currentPeriodQuantity', 'price'])
                    this.page.total = res.totalCount
                    // 本页初始的总计；查询章次的总计
                    const query = {
                        id: this.id,
                        billQuantitiesType: Number(this.leftTab),
                        chapterSequenceCode: this.chapterSequence.listSubitemCode,
                    }
                    this.model.chapterTotalCount({...query}).then(total => {
                        this.chapterTotal = total
                        const initPageTotal = this.sumLeafValues(this.list)
                        this.chapterBesidesPageTotal = this.chapterTotal - initPageTotal
                    })
                } else {
                    this.list = []
                    this.page.total = 0
                }
            }).finally(() => {
                this.listLoading = false
            })
        },
        // 叶子节点的本期金额累加
        sumLeafValues(tree) {
            let sum = 0
            function accumulate(nodes) {
                nodes.forEach(node => {
                    if (node.childrenList && node.childrenList.length) {
                        accumulate(node.childrenList)
                    } else {
                        if (node.unitCode === 'zonge') {
                            // 避免输入文字的情况，要转一下，同时输入的时候也需限制
                            const currentPeriodMsAmount = Number(node.currentPeriodMsAmount) ? node.currentPeriodMsAmount : 0
                            sum = calcNumber(`${sum}+${currentPeriodMsAmount}`)
                        } else {
                            const currentPeriodQuantity = Number(node.currentPeriodQuantity) ? node.currentPeriodQuantity : 0
                            const price = Number(node.price) ? node.price : 0
                            // console.log('currentPeriodQuantity', currentPeriodQuantity)
                            // console.log('price', price)
                            const multipul = calcNumber(`${currentPeriodQuantity}*${price}`)
                            sum = calcNumber(`${sum}+${multipul}`)
                        }
                    }
                })
            }
            accumulate(tree)
            return sum
        },
        // 把叶子节点push进入一个数组中
        sumLeafArr(tree) {
            const arr = []
            function accumulate(nodes) {
                nodes.forEach(node => {
                    if (node.childrenList && node.childrenList.length) {
                        accumulate(node.childrenList)
                    } else {
                        if (node.hasChildren === 2) {
                            arr.push({
                                ...node,
                                currentPeriodMsAmount: Number(node.currentPeriodMsAmount) ? node.currentPeriodMsAmount : 0,
                                currentPeriodQuantity: Number(node.currentPeriodQuantity) ? node.currentPeriodQuantity : 0
                            })
                        }
                    }
                })
            }
            accumulate(tree)
            return arr
        },
        // 把每一行的form push 进一个数组中
        sumLeafFromValid(tree) {
            const arr = []
            const _this = this
            function accumulate(nodes) {
                nodes.forEach(async(node, index) => {
                    if (node.childrenList && node.childrenList.length) {
                        accumulate(node.childrenList)
                    } else {
                        if (node.hasChildren === 2 && node.unitCode === 'zonge') {
                            const refName = `formTable-${node.id}-currentPeriodMsAmount`
                            arr.push(_this.$refs[refName].validate())
                        }
                        if (node.hasChildren === 2 && node.unitCode !== 'zonge') {
                            const refName = `formTable-${node.id}-currentPeriodQuantity`
                            arr.push(_this.$refs[refName].validate())
                        }
                    }
                })
            }
            accumulate(tree)
            return arr
        },
        // 清除校验
        sumLeafFromValidClear(tree) {
            const arr = []
            const _this = this
            function accumulate(nodes) {
                console.log(nodes)
                if (nodes) {
                    nodes.forEach((node) => {
                        if (node.childrenList && node.childrenList.length) {
                            accumulate(node.childrenList)
                        } else {
                            if (node.hasChildren === 2 && node.unitCode === 'zonge') {
                                const refName = `formTable-${node.id}-currentPeriodMsAmount`
                                _this.$refs[refName].clearValidate()
                            }
                            if (node.hasChildren === 2 && node.unitCode !== 'zonge') {
                                const refName = `formTable-${node.id}-currentPeriodQuantity`
                                _this.$refs[refName].clearValidate()
                            }
                        }
                    })
                }
            }
            accumulate(tree)
            return arr
        },
        validAllFrom() {
            return new Promise((resolve, reject) => {
                const validArr = this.sumLeafFromValid(this.list)
                Promise.all(validArr).then(() => {
                    // console.log('验证成功')
                    resolve()
                }).catch(() => {
                    // console.log('验证失败')
                    reject()
                })
            })
        },
        // 保存
        handleSave(isbtn) {
            return new Promise((resolve, reject) => {
                this.validAllFrom().then(() => {
                    const listData = this.sumLeafArr(this.list)
                    if (listData.length) {
                        const data = {
                            id: this.id,
                            projectId: this.info.projectId,

                            billQuantitiesType: listData[0].type,
                            list: listData.map(el => {
                                return {
                                    chapterSequenceCode: el.chapterSequenceCode,
                                    listSubitemCode: el.listSubitemCode,
                                    currentPeriodQuantity: Number(el.currentPeriodQuantity),
                                    currentPeriodMsAmount: Number(el.currentPeriodMsAmount),
                                    remark: el.remark,
                                    unitCode: el.unitCode, // 单位编码
                                }
                            })
                        }
                        this.model.currentPeriodSave({...data}).then(res => {
                            if (isbtn) {
                                this.$message({
                                    type: 'success',
                                    message: '计量申请草稿保存成功!',
                                })
                            }
                            this.isFirst = false
                            resolve()
                            this.sumLeafFromValidClear()
                        }).catch((err) => {
                            console.log(err)
                            reject()
                        })
                        // 无list的不请求接口
                    } else {
                        resolve()
                    }
                }).catch(() => {
                    reject()
                })
            })
        },
        // 上一步
        handleBack() {
            this.handleSave().then(() => {
                this.$emit('back')
            })
        },
        // 下一步
        handleNext() {
            this.handleSave().then(() => {
                this.model.checkTotalAmount({id: this.id}).then(res => {
                    this.$emit('next')
                })
            })
        },
        // 正整数(非负整数)
        checkPositiveInteger(rule, value, callBack) {
            const reg = /^[0-9]*[1-9][0-9]*$/ 
            if (value) {
                if (!reg.test(String(value))) {
                    console.log('输入数字应为正整数')
                    callBack(new Error('输入数字应为正整数'))
                } else {
                    callBack()
                }
            } else {
                callBack()
            }
            // callBack(new Error('输入数字应为正整数'))
        },
        // 保留两位小数
        checkTwoDecimal(rule, value, callBack) {
            const reg = /^([0-9][0-9]*)+(.[0-9]{1,2})?$/
            // console.log('value', value) // 输出来的没有小数点
            if (value) {
                if (!reg.test(String(value))) {
                    // console.log('输入数字最多保留两位小数，且为正数')
                    callBack(new Error('输入数字最多保留两位小数，且为正数'))
                } else {
                    callBack()
                }
            } else {
                callBack()
            }
        },
        // 保留三位小数
        checkThreeDecimal(rule, value, callBack) {
            const reg = /^([0-9][0-9]*)+(.[0-9]{1,3})?$/
            if (value) {
                if (!reg.test(String(value))) {
                    callBack(new Error('输入数字最多保留三位小数，且为正数'))
                } else {
                    callBack()
                }
            } else {
                callBack()
            }
        },
    }
  
}
</script>
<style lang="scss" scoped>
.current-prriod-quantities{
   width: 100%;
   font-size: 14px;
   .model-title{
        display: flex;
        align-items: center;
        width: 100%;
        padding: 16px 24px;
        border-bottom: 1px solid rgba(131, 145, 178, 0.1);
        margin-bottom: 8px;
    }
  .top{
    display: flex;
    width: 100%;
    height:65vh;
    .left {
      width: 280px;
      height: 100%;
      margin-right: 16px;
      flex-shrink: 0;
      border: 1px solid #f0f4f7;
      box-shadow: 0px 0px 4px 0px rgba(131, 145, 178, 0.14);
      padding: 24px 16px;
      .list {
          height: calc(100% - 38px);
          overflow-y: auto;
          .active{
            background: #f0f4f7;
            color: #000;
          }
          .list-item{
            cursor: pointer;
            font-size: 14px;
            padding: 8px 0px;
            display: flex;
            align-items: center;
            justify-content: center;
            
            &:hover{
              background: #f0f4f7;
              color: #000;
            }
            .icon{
              font-size: 20px;
              margin-right: 6px;
            }
          } 
      }
    }
    .right{
        flex: 1;
        .model-title{
            padding: 12px 0px;
        }
        ::v-deep{
            .el-form-item{
                margin-bottom: 0px !important;
            }
        }
          /* 替换默认展开收起图片 */
        ::v-deep {
            .el-table__expand-icon {
                width: 16px;
                height: 16px;
                background: url("~@/assets/images/zhankai.png") no-repeat;
                background-size: 100% 100%;
                margin-left: -20px;
                flex-shrink: 0;
                .el-icon-arrow-right {
                    display: none;
                }
            }
            .el-table__expand-icon--expanded {
                transform: none;
                background: url("~@/assets/images/shouqi.png") no-repeat;
                background-size: 100% 100%;
                flex-shrink: 0;
            }
            .custom-td .cell {
                display: flex;
                align-items: center;
            }
            .el-table .cell.el-tooltip{
                display: flex;
                align-items: center;
            }
        }
        .icon-flex {
            display: flex;
            align-items: center;
            line-height: 1.5;

            .file-icon {
                width: 22px;
                font-size: 22px;
                margin-right: 4px;
                flex-shrink: 0;
            }
            .catalogue-icon {
                width: 20px;
                font-size: 18px;
                margin-right: 4px;
                flex-shrink: 0;
            }
        }
        .pagination{
            text-align: right;
        }
    }
  }
  .btn{
    width: 100%;
    display: flex;
    justify-content: center;
    // position: absolute;
    margin-bottom: 24px;
  }
}
</style>
